"""
Word bank loader module
"""

import os
import json
import random
from typing import List, Dict, Any, Optional

from .word_banks import WORD_BANKS_CONFIG

class WordBankLoader:
    def __init__(self):
        self.project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.word_banks_dir = os.path.join(self.project_root, 'data', 'word_banks')
        
    def get_word_bank_info(self, bank_id: str) -> Optional[Dict[str, Any]]:
        """获取词库信息"""
        return WORD_BANKS_CONFIG.get(bank_id)
        
    def list_available_word_banks(self) -> List[Dict[str, Any]]:
        """列出所有可用的词库"""
        available_banks = []
        for bank_id, config in WORD_BANKS_CONFIG.items():
            json_path = os.path.join(self.word_banks_dir, config['file'])
            if os.path.exists(json_path):
                bank_info = config.copy()
                bank_info['id'] = bank_id
                bank_info['word_count'] = self._get_word_count(json_path)
                available_banks.append(bank_info)
        return available_banks
        
    def _get_word_count(self, json_path: str) -> int:
        """获取词库中的单词数量"""
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                word_bank = json.load(f)
                return len(word_bank.get('words', []))
        except:
            return 0
            
    def load_word_bank(self, bank_id: str, count: int = None) -> List[Dict[str, Any]]:
        """加载指定词库的单词
        
        Args:
            bank_id: 词库ID
            count: 需要的单词数量，如果为None则返回全部
            
        Returns:
            单词列表，每个单词是一个字典，包含单词信息
        """
        bank_info = self.get_word_bank_info(bank_id)
        if not bank_info:
            print(f"Bank info not found for {bank_id}")  # 调试信息
            return []
            
        json_path = os.path.join(self.word_banks_dir, bank_info['file'])
        if not os.path.exists(json_path):
            print(f"JSON file not found: {json_path}")  # 调试信息
            return []
            
        try:
            print(f"Loading words from {json_path}")  # 调试信息
            with open(json_path, 'r', encoding='utf-8') as f:
                word_bank = json.load(f)
                words = word_bank.get('words', [])
                print(f"Loaded {len(words)} words from file")  # 调试信息
                
            if count is None:
                return words
                
            # 随机选择指定数量的单词
            selected = random.sample(words, min(count, len(words)))
            print(f"Selected {len(selected)} words randomly")  # 调试信息
            return selected
            
        except Exception as e:
            print(f"Error loading word bank {bank_id}: {str(e)}")  # 调试信息
            return []
            
    def get_word_details(self, bank_id: str, word: str) -> Optional[Dict[str, Any]]:
        """获取单词的详细信息
        
        Args:
            bank_id: 词库ID
            word: 要查询的单词
            
        Returns:
            单词的详细信息字典，如果未找到则返回None
        """
        bank_info = self.get_word_bank_info(bank_id)
        if not bank_info:
            return None
            
        json_path = os.path.join(self.word_banks_dir, bank_info['file'])
        if not os.path.exists(json_path):
            return None
            
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                word_bank = json.load(f)
                words = word_bank.get('words', [])
                
            for word_info in words:
                if word_info['word'].lower() == word.lower():
                    return word_info
                    
            return None
            
        except Exception as e:
            print(f"Error getting word details: {str(e)}")
            return None
            
    def search_words(self, bank_id: str, query: str) -> List[Dict[str, Any]]:
        """搜索词库中的单词
        
        Args:
            bank_id: 词库ID
            query: 搜索关键词
            
        Returns:
            匹配的单词列表
        """
        bank_info = self.get_word_bank_info(bank_id)
        if not bank_info:
            return []
            
        json_path = os.path.join(self.word_banks_dir, bank_info['file'])
        if not os.path.exists(json_path):
            return []
            
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                word_bank = json.load(f)
                words = word_bank.get('words', [])
                
            query = query.lower()
            results = []
            
            for word_info in words:
                # 匹配单词
                if query in word_info['word'].lower():
                    results.append(word_info)
                    continue
                    
                # 匹配释义
                if query in word_info['definition'].lower():
                    results.append(word_info)
                    continue
                    
            return results
            
        except Exception as e:
            print(f"Error searching words: {str(e)}")
            return []